package classes;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;

public class Part4 extends JFrame implements ActionListener{
	
	public static final int WINDOW_WIDTH = 400;
	public static final int WINDOW_HEIGHT = 250;
	public static final int NUMBER_OF_CHAR = 30;
	public static final double LEFT = 0;
	public static final double RIGHT = 1;
	
	private JTextField number;
	private JLabel resultLabel;
	private float epsilon ;
	private static int noOfThreads;
	
	
	public static synchronized void setNoOfThreads(){
		noOfThreads +=1;
	}
	
	public static synchronized int getNoOfThreads(){
		return noOfThreads ;
	}
	
	public static void main(String[] args)
	 {
		Part4 window = new Part4();
		window.setVisible(true);
	 }
	public Part4()
	{
	 super("adaptive quadrature");
	 setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
	 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	 setLayout(new GridLayout(1, 1));
	 getContentPane().setBackground(Color.white);
	 
	
	 JPanel dartPanel = new JPanel();
	 
	 
	
	 dartPanel.setLayout(new GridLayout(5, 1));
	 dartPanel.setBackground(Color.GREEN);
	 
	 number = new JTextField(NUMBER_OF_CHAR);
	 
	 JLabel dartLabel = new JLabel("Enter Epsilon:");
	 resultLabel = new JLabel();
	 //dartPanel.add(dartLabel, BorderLayout.LINE_END);
	
	 JButton actionButton = new JButton("calculate Pi");
	 actionButton.addActionListener(this);
	 dartPanel.add(dartLabel , -1);
	 dartPanel.add(number, BorderLayout.NORTH);
	 dartPanel.add(actionButton);
	 dartPanel.add(resultLabel,BorderLayout.SOUTH);
	
	 add(dartPanel);
	 
	
	}

	
	
	public void actionPerformed(ActionEvent e)
	{
	
		double Pi;
		epsilon = Float.parseFloat(number.getText());
		noOfThreads = 0;
		
		p4Thread th = new p4Thread(LEFT,RIGHT,Math.sqrt(1-LEFT*LEFT),Math.sqrt
				(1-RIGHT*RIGHT),(RIGHT -LEFT)*(RIGHT -LEFT),epsilon);
		
		double startTime = System.currentTimeMillis();
		th.start();
		try {
			th.join();
			
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		double duration = System.currentTimeMillis() - startTime ;
		Pi = (4 * (th.getLarea() + th.getRarea())) / ((RIGHT -LEFT)*(RIGHT -LEFT));
		
		resultLabel.setText("<html><p align=\"left\">The Pi is: " + 
				String.valueOf(Pi) + "<br>the program created: " +
				noOfThreads + " number of threads and<br>execution time is: " +
				String.valueOf(duration) + " ms");
		
	}
	

}


